<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/1/6
 * Time: 10:13
 */
namespace app\web\service;

use app\web\model\Goods;
use app\web\model\GoodsSku;
use app\web\util\AlibabaUtil;

class GoodsService{
    /**
     * @todo 在售商品列表
     * @author ZJF
     */
    public function getGoodsList($shop_id = 0,$param = []){
        if(empty($shop_id) || !is_numeric($shop_id)){
            return array_response([],1,"无效的店铺ID");
        }
        if(empty($param)){
            return array_response([],1,"无效的基础配置");
        }
        $shop_name = empty($param['shop_name'])?'':$param['shop_name'];
        $limit = empty($param['limit'])?10:$param['limit'];
        $page = empty($param['page'])?1:$param['page'];
        $status = empty($param['status'])?0:$param['status'];
        $category_id = empty($param['category_id'])?0:$param['category_id'];
        $goods_name = empty($param['goods_name'])?'':$param['goods_name'];
        $show_sku = empty($param['show_sku'])?0:$param['show_sku'];
        //获取在售1688商品
        $ali_util = new AlibabaUtil();
        $ali_service = new AliService();
        $ali_param = array(
            'pageNo'=>$page,
            'pageSize'=>$limit,
            'statusList'=>$ali_service->changeStatusList($status)
        );
        if(!empty($goods_name)){
            $ali_param['subjectKey'] = $goods_name;
        }
        if(!empty($category_id)){
            $ali_param['categoryId'] = $category_id;
        }
        $product_list = $ali_util->productList($shop_id,$ali_param);
        if($product_list['code'] != 0){
            return $product_list;
        }
        $product_list = $product_list['data']['result']['pageResult'];
        //提取商品productID
        $product_ids = array_column($product_list['resultList'],'productID');
        //获取商品成功，查询商品是否在数据库中存在，且，设置过简称
        $goods_model = new Goods();
        $goods_list = $goods_model
                    ->field("id,shop_id,product_id,short_name")
                    ->where("shop_id='{$shop_id}' AND product_id IN ('".implode("','",$product_ids)."')")
                    ->select();
        $goods_list = ObjectToArray($goods_list);
        $goods_column = [];
        if(!empty($goods_list)){
            $goods_column = array_column($goods_list,'short_name','product_id');
        }
        $list = [];
//        print_data($product_list['resultList']);
        foreach($product_list['resultList'] as $val){
            //商品数据
            $image = empty($val['image']['images'][0])?'':$val['image']['images'][0];
            if(!empty($image) && !strstr($image,'http:') && !strstr($image,'https:')){
                $image = "https://cbu01.alicdn.com/".$image;
            }
            $list[$val['productID']] = array(
                'product_id'=>$val['productID'],
                'shop_name'=>$shop_name,
                'goods_name'=>$val['subject'],
                'short_name'=>empty($goods_column[$val['productID']])?'':$goods_column[$val['productID']],
                'images'=>$image,
                'category_name'=>$val['categoryName'],
                'category_id'=>$val['categoryID'],
                'product_cargo_number'=>'',
                'goods_sku_list'=>[]
            );
            //商品sku信息
            if(isset($val['skuInfos'])){
                foreach($val['skuInfos'] as $sku_info_val){
                    $sku_name = implode('',array_column($sku_info_val['attributes'],'attributeValue'));
                    $list[$val['productID']]['goods_sku_list'][$sku_info_val['specId']] = array(
                        'sku_name'=>$sku_name,
                        'attribute_id'=>'',
                        'sku_code'=>$sku_info_val['skuCode'],
                        'sku_id'=>$sku_info_val['skuId'],
                        'spec_id'=>$sku_info_val['specId'],
                        'short_name'=>''
                    );
                }
            }
        }
        //商品规格数据
        if(!empty($show_sku) && !empty($product_ids)){
            $sku_model = new GoodsSku();
            $sku_list = $sku_model
                        ->field("id,shop_id,product_id,spec_id,short_name")
                        ->where("shop_id='{$shop_id}' AND product_id IN ('".implode("','",$product_ids)."')")
                        ->select();
            $sku_list = ObjectToArray($sku_list);
//            print_data($sku_list);
            foreach($sku_list as $sku_val){
                //填充sku简称
                $list[$sku_val['product_id']]['goods_sku_list'][$sku_val['spec_id']]['short_name'] = $sku_val['short_name'];
            }
        }
        //重置数组下标
        foreach($list as &$l_val){
            $l_val['goods_sku_list'] = array_values($l_val['goods_sku_list']);
        }
        //最终数据
        $data = array(
            'total'=>$product_list['totalRecords'],
            'per_page'=>$limit,
            'current_page'=>$page,
            'last_page'=>ceil($product_list['totalRecords']/$limit),
            'data'=>empty($list)?[]:array_values($list)
        );
        return $data;
    }

    /**
     * @todo 获取自定义分类
     * @author ZJF
     */
    public function getCatlist($shop_id = 0,$param = []){
        if(empty($shop_id) || !is_numeric($shop_id)){
            return array_response([],1,"无效的店铺ID");
        }
        if(empty($param)){
            return array_response([],1,"无效的基础配置");
        }
        $member_id = empty($param['member_id'])?'':$param['member_id'];
        if(empty($member_id)){
            return array_response([],1,"无效的会员ID");
        }
        $ali_util = new AlibabaUtil();
        $res = $ali_util->getSelfCatlist($shop_id,$member_id);
        if($res['code']!=0){
            return array_response([],1,"获取分类失败");
        }
        return empty($res['data']['result']['toReturn'][0]['sellerCats'])?[]:$res['data']['result']['toReturn'][0]['sellerCats'];
    }

    /**
     * @todo 编辑商品
     * @author ZJF
     */
    public function editGoods($shop_id = 0,$param = []){
        if(empty($shop_id) || !is_numeric($shop_id)){
            return array_response([],1,"无效的店铺ID");
        }
        if(empty($param)){
            return array_response([],1,"无效的基础配置");
        }
        $data = empty($param['data'])?[]:$param['data'];
        if(empty($data) || !is_array($data)){
            return array_response([],1,"无效的商品数据");
        }
        $sku_data = [];
        //获取全部商品ID
        $goods_product_ids = array_column($data,'product_id');
        if(empty($goods_product_ids)){
            return array_response([],1,"无效的商品数据");
        }
        $now_time = date('Y-m-d H:i:s');
        //查询商品数据
        $goods_model = new Goods();
        $goods_list = $goods_model
                    ->where("shop_id='{$shop_id}' AND product_id IN ('".implode("','",$goods_product_ids)."')")
                    ->select();
        $goods_list = ObjectToArray($goods_list);
        $goods_insert_data = [];
        $goods_update_data = [];
        if(empty($goods_list)){
            //没有商品信息，全部新增操作
            foreach($data as $goods_val){
                $goods_insert_data[] = array(
                    'shop_id'=>$shop_id,
                    'product_id'=>$goods_val['product_id'],
                    'subject'=>$goods_val['goods_name'],
                    'images'=>$goods_val['images'],
                    'category_name'=>$goods_val['category_name'],
                    'category_id'=>$goods_val['category_id'],
                    'short_name'=>$goods_val['short_name'],
                    'ctime'=>$now_time,
                    'mtime'=>$now_time
                );
                //提取需要编辑的sku数据
                if(!empty($goods_val['goods_sku_list'])){
                    foreach($goods_val['goods_sku_list'] as $sku_val){
                        $sku_data[] = array(
                            'product_id'=>$goods_val['product_id'],
                            'sku_name'=>$sku_val['sku_name'],
                            'sku_code'=>$sku_val['sku_code'],
                            'sku_id'=>$sku_val['sku_id'],
                            'spec_id'=>$sku_val['spec_id'],
                            'sku_short_name'=>$sku_val['short_name']
                        );
                    }
                }
            }
        }
        else{
            $old_goods_product_ids = array_column($goods_list,'product_id','id');
            foreach($data as $goods_val){
                if(in_array($goods_val['product_id'],$old_goods_product_ids)){
                    //存在修改
                    $goods_update_data[] = array(
                        'id'=>array_search($goods_val['product_id'],$old_goods_product_ids),
                        'shop_id'=>$shop_id,
                        'product_id'=>$goods_val['product_id'],
                        'subject'=>$goods_val['goods_name'],
                        'images'=>$goods_val['images'],
                        'category_name'=>$goods_val['category_name'],
                        'category_id'=>$goods_val['category_id'],
                        'short_name'=>$goods_val['short_name'],
                        'mtime'=>$now_time
                    );
                }
                else{
                    //不存在新增
                    $goods_insert_data[] = array(
                        'shop_id'=>$shop_id,
                        'product_id'=>$goods_val['product_id'],
                        'subject'=>$goods_val['goods_name'],
                        'images'=>$goods_val['images'],
                        'category_name'=>$goods_val['category_name'],
                        'category_id'=>$goods_val['category_id'],
                        'short_name'=>$goods_val['short_name'],
                        'ctime'=>$now_time,
                        'mtime'=>$now_time
                    );
                }
                //提取需要编辑的sku数据
                if(!empty($goods_val['goods_sku_list'])){
                    foreach($goods_val['goods_sku_list'] as $sku_val){
                        $sku_data[] = array(
                            'product_id'=>$goods_val['product_id'],
                            'sku_name'=>$sku_val['sku_name'],
                            'sku_code'=>$sku_val['sku_code'],
                            'sku_id'=>$sku_val['sku_id'],
                            'spec_id'=>$sku_val['spec_id'],
                            'sku_short_name'=>$sku_val['short_name']
                        );
                    }
                }
            }
        }
        if(!empty($goods_insert_data)){
            //新增商品信息
            $goods_insert_res = $goods_model->insertAll($goods_insert_data);
            if(false === $goods_insert_res){
                return array_response([],1,"保存商品信息失败");
            }
        }
        if(!empty($goods_update_data)){
            //编辑商品信息
            $goods_update_res = $goods_model->saveAll($goods_update_data);
            if(false === $goods_update_res){
                return array_response([],1,"编辑商品信息失败");
            }
        }
//        print_data($sku_data);
        //无需要编辑的sku信息
        if(empty($sku_data)){
            return true;
        }
        //获取skuid集合
        $sku_ids = array_column($sku_data,'sku_id');
        if(empty($sku_ids)){
            return true;
        }
        //获取全部sku信息
        $goods_sku_model = new GoodsSku();
        $sku_list = $goods_sku_model
                    ->where("shop_id='{$shop_id}' AND product_id IN('".implode("','",$goods_product_ids)."') AND sku_id IN('".implode("','",$sku_ids)."')")
                    ->select();
        $sku_list = ObjectToArray($sku_list);
        $sku_insert_data = [];
        $sku_update_data = [];
        if(empty($sku_list)){
            foreach($sku_data as $sku_val){
                $sku_insert_data[] = array(
                    'shop_id'=>$shop_id,
                    'product_id'=>$sku_val['product_id'],
                    'sku_name'=>$sku_val['sku_name'],
                    'sku_code'=>$sku_val['sku_code'],
                    'sku_id'=>$sku_val['sku_id'],
                    'spec_id'=>$sku_val['spec_id'],
                    'short_name'=>$sku_val['sku_short_name'],
                    'ctime'=>$now_time,
                    'mtime'=>$now_time
                );
            }
        }
        else{
            $old_sku_ids = array_column($sku_list,'sku_id','id');
            foreach($sku_data as $sku_val){
                if(in_array($sku_val['sku_id'],$old_sku_ids)){
                    //存在修改
                    $sku_update_data[] = array(
                        'id'=>array_search($sku_val['sku_id'],$old_sku_ids),
                        'shop_id'=>$shop_id,
                        'product_id'=>$sku_val['product_id'],
                        'sku_name'=>$sku_val['sku_name'],
                        'sku_code'=>$sku_val['sku_code'],
                        'sku_id'=>$sku_val['sku_id'],
                        'spec_id'=>$sku_val['spec_id'],
                        'short_name'=>$sku_val['sku_short_name'],
                        'mtime'=>$now_time
                    );
                }
                else{
                    //不存在新增
                    $goods_insert_data[] = array(
                        'shop_id'=>$shop_id,
                        'product_id'=>$sku_val['product_id'],
                        'sku_name'=>$sku_val['sku_name'],
                        'sku_code'=>$sku_val['sku_code'],
                        'sku_id'=>$sku_val['sku_id'],
                        'spec_id'=>$sku_val['spec_id'],
                        'short_name'=>$sku_val['sku_short_name'],
                        'mtime'=>$now_time,
                        'ctime'=>$now_time
                    );
                }
            }
        }
        if(!empty($sku_insert_data)){
            //新增sku信息
            $sku_insert_res = $goods_sku_model->insertAll($sku_insert_data);
            if(false === $sku_insert_res){
                return array_response([],1,"保存规格信息失败");
            }
        }
        if(!empty($sku_update_data)){
            //编辑sku信息
            $sku_update_res = $goods_sku_model->saveAll($sku_update_data);
            if(false === $sku_update_res){
                return array_response([],1,"编辑规格信息失败");
            }
        }
        return true;
    }
}